<template>
  <div class="custom-btn" @click="updateView" ref="switchRef">
    <span v-if="isDark" class="fa-solid fa-moon"></span>
    <span v-else class="fa-solid fa-sun"></span>
  </div>
</template>

<script setup>
import { ref } from 'vue'

let isDark = ref(false)
let switchRef = ref(null)

function changeTheme() {
  isDark.value = !isDark.value
  document.documentElement.setAttribute('data-theme', isDark.value ? 'dark' : '')
}

function updateView(event) {
  if (!document.startViewTransition) {
    changeTheme()
    return
  }

  const transition = document.startViewTransition(() => changeTheme())

  transition.ready.then(() => {
    const x = event.clientX
    const y = event.clientY
    const endRadius = Math.hypot(
      Math.max(x, innerWidth - x),
      Math.max(y, innerHeight - y)
    )

    const clipPath = [
      `circle(0px at ${x}px ${y}px)`,
      `circle(${endRadius}px at ${x}px ${y}px)`
    ]

    document.documentElement.animate(
      {
        clipPath: isDark.value ? [...clipPath].reverse() : clipPath,
      },
      {
        duration: 400,
        easing: 'ease-in',
        pseudoElement: isDark.value
          ? '::view-transition-old(root)'
          : '::view-transition-new(root)'
      }
    )
  })
}
</script>

<style scoped>

</style>

<style>
::view-transition-old(root),
::view-transition-new(root) {
  height: auto;
  width: 100vw;
  animation: none;
  mix-blend-mode: normal;
}

html[data-theme="dark"]::view-transition-old(root) {
  z-index: 2147483646;
}

html[data-theme="dark"]::view-transition-new(root) {
  z-index: 1;
}

html::view-transition-old(root) {
  z-index: 1;
}

html::view-transition-new(root) {
  z-index: 2147483646;
}
</style>